package com.ckzp.weixin.service.aes;


import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.jfinal.log.Log;

/**
 * Created by 51594 on 2024/2/29.
 */
public class WxDataAes {


    public static Log log = com.jfinal.log.Log.getLog(WxDataAes.class);

    /**
     * 微信前端加密数据解密算法
     * <p/>
     * 对称解密的目标密文为 Base64_Decode(encryptedData)。
     * 对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节。
     * 对称解密算法初始向量 为Base64_Decode(iv)，其中iv由数据接口返回。
     * <p/>
     * * @param encrypted 加密数据
     * * @param session_key 会话** session_key,从登陆反加的接口中取得，每个用户的session_key不一样
     * * @param iv 加密算法的初始向量
     */
    public static String wxDecrypt(String encrypted, String session_key, String iv) {
        try {

            byte[] encrypted64 = Base64Decoder.decode(encrypted);
            byte[] key64 = Base64Decoder.decode(session_key);
            byte[] iv64 = Base64Decoder.decode(iv);
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding,
                    new SecretKeySpec(key64, "AES"),
                    new IvParameterSpec(iv64));
            byte[] decryptDataBase64 = aes.decrypt(encrypted64);
            return new String(decryptDataBase64, "UTF-8");
        } catch (Exception e) {
            log.error("微信解密失败", e);
            log.error("--encrypted-" + encrypted + "---");
            log.error("--session_key-" + session_key + "---");
            log.error("--iv-" + iv + "---");
            return null;
        }
    }

    /**
     * 加密
     *
     * @param encrypted   原文
     * @param session_key base64后的key
     * @param iv          base64后的iv
     * @return base64后的字符串
     */
    public static String wxEncrypt(String encrypted, String session_key, String iv) {
        try {
            byte[] key64 = Base64Decoder.decode(session_key);
            byte[] iv64 = Base64Decoder.decode(iv);
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding,
                    new SecretKeySpec(key64, "AES"),
                    new IvParameterSpec(iv64));
            return aes.encryptBase64(encrypted, "UTF-8");
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] arg) {
        String s = "{\"encrypted\":\"ahVG20pyG3sbloQkeYP6LpDWP4Q5BCY77xesjuSaY0NFgC3iSwu/VjaxZXwwu/hFEvT+6fzoTHhr8uqtjLOuVR9rABPNpBc56+CsnNpUhQW28flwHzFluOalP8aZHTcWNSV0KzFO4dnQ7ZPdRDTdPhcT7B75lP41NZ84w9pBVITo1Q5SoNXyaNJ4tsjz0Ef4PK6NwJVwi/z1VfzIbpw7t2qyQu4VDF908j/hNRVodmXxHcXd3FvfvV019veE1EntdMJHi0ruCaUXxUBZClMnXSRslgvSxft24ixejQWyORYzSr5XZfKgs5Mr95q4MLzGzPS1NrE2s84Ffm1mM2YvOIgqjr1IS3Ra9qTdM9wxvmn+nWY6uNtwzPteyCxe3ZTLls8JMQmotjP6VMiQSWJPaIrpz2JWQI7M53zdua7SHQSITLJckMMGRWPHv9qIzIMv+Y0rHeaODu4vbx1WvIRZeyIggxIoQ0HhL1zXT7dsp+mQG4uU32JNPgKSFpeu7QMZuvD2nopa2k6BT4a0SdJSI+6+IpkKU2gBpWhgsyMgMklGpZMAATHIRAuBOz1DPyBsZT9XWovypry7n80j3lJ9QKulwDz1kQX/kINUwrCqD8xDNsZWX/fD2N8R6SXp4GyqEj0g+AlMdEC4bTW+zUGMbfVg0lUTADxDRCxtJHXawm5RwwGozEGhtIucCh9j4RX3T6xNV55seajdwcoulzrtb3aqIxSwUUiUKFquiBRPfD5ckkKTdDf0ETq1hudJE3b+pWGpySDqmvL+zVCYOqbm9sNh5M8p7mCJPzIm112+UN+qXV0bOfizW//1W4DcRX5v79F5DdIeznPSOeqiV1SoBRCzVMLRkNToQuH/55rVHVhesSqMLniR14gXsUY/XWkpEUoAQaT1p8zb3I3HZvze3gXYGAcUA0Gg05QkuNKPgJFJvUlqcnwbueoqdFesLxYfRKcSE5r6PdB27BbEdEZQhh1AayxV3T+5iY2zz3aIvtak0dEzcC9KTpoHayVMF83I6HfHXbHj9+HsBBMn9vxZMtFGVIfYcKM5sIAEWrNp04AnkhhG8BfSSJai4Ta/3cWCNwQ0wChbZFaDGkvPLbhn6qNcSuTPkyhgKyK9xIH4VT0pJuTm6bpqD+SzSQd9V44I/cU6M42Y+ds0ba4AYGnD90z2XR4Dv1Z6j3usMx2Peufizc8vc5/UfCUPbgApZujYCFNxKPJNIWJGsc6dsyvrxCw+GCqQ3GHtgrPxF9lsGf01yH2xh7zRZfphf+rijtQRMNFf7jNmABeOJt7HNb45pijkj2GTaUgrSE88/W0JyKYFFdDzxjJJ8J4fEysYmtuGPY6mAYQ7J2CCNj34XKis15E+JUUfJPagnL/tB67vPVExRS1ZFQ/JYQibYMo3OejD+205Qf/aSByPcfVdOBnxhHXVEdpu7PsSqefjr1Qvc56D1i1XzQbmcWwXv4rd+1izz0tn70VlC3I4ha7tX5GcXU1exLs5ztCOQlooXO7jPCI4RsGzy3R8Vlpw9Qa2lRk2Gv4Fa/plen+Kex/mICDWGpXE4XfXGBaIqyOkQZLl/jc=\",\"session_key\":\"81_ipyuR3HRes35Nh9VpkCydLZZrsCRE22ehPi25ZbXT4xTf-7RfQubv21awIs\",\"iv\":\"nsjiGZaI3AEM24YztTnaPg==\",\"times\":1717474987505}";
        System.out.println(wxDecrypt(s, "gbVmSaSTmEYSTn3tsIPPBQ==", "n5lcfPF/p7NItYuSTL60Mw=="));
        //  String s1 = "{a:1}";
        //    System.out.println(wxEncrypt(s1, "gM/qVa54ZuNDmU4w43flsg==", "C4PM4ZrBrhQAi1w77yjY2w=="));
    }

}
